import type { CompanyDetail, CompanyItem, CompanyListQuery, CompanyOptions, CreateOrUpdateCompanyRequest } from "@/pages/internship/company/apis/type"
import { ElMessage } from "element-plus"
import { defineStore } from "pinia"
import { reactive, ref } from "vue"
import { createCompanyApi, deleteCompanyApi, getCompanyDetailApi, getCompanyForUpdateApi, getCompanyListApi, getCompanyOptionsApi, updateCompanyApi, uploadLicenseApi } from "@/pages/internship/company/apis"
import { pinia } from ".."
import { useUserStore } from "./user"

// 定义常量和类型
const DEFAULT_QUERY_PARAMS: CompanyListQuery = {
  keyword: "",
  companyType: undefined,
  companyScale: undefined,
  workCity: undefined,
  status: undefined,
  page: 1,
  size: 10
}

export const useCompanyStore = defineStore("company", () => {
  // 状态管理 - 添加明确的类型注解
  const companyList = ref<CompanyItem[]>([])
  const total = ref<number>(0)
  const loading = ref<boolean>(false)
  const detailLoading = ref<boolean>(false) // 添加详情加载状态
  const optionsLoading = ref<boolean>(false) // 添加选项加载状态
  const submitLoading = ref<boolean>(false) // 提交加载状态
  const options = reactive<CompanyOptions>({
    workCityOptions: [],
    companyTypeOptions: [],
    companyScaleOptions: []
  })
  const currentDetail = ref<CompanyDetail | null>(null)
  const queryParams = reactive<CompanyListQuery>({ ...DEFAULT_QUERY_PARAMS })

  // 统一错误处理函数
  const handleApiError = (error: unknown, message: string): never => {
    console.error(message, error)
    ElMessage.error(message)
    throw error // 重新抛出以便上层组件可以捕获
  }

  // 获取公司列表
  const fetchCompanyList = async (isRefresh = false): Promise<void> => {
    if (loading.value) return // 防止重复请求

    if (isRefresh) {
      queryParams.page = 1
    }
    loading.value = true
    try {
      const response = await getCompanyListApi(queryParams)
      if (response?.data) {
        companyList.value = response.data.records || []
        total.value = response.data.total || 0
      }
    } catch (error) {
      handleApiError(error, "获取公司列表失败")
    } finally {
      loading.value = false
    }
  }

  // 获取选项数据
  const fetchOptions = async (): Promise<void> => {
    if (optionsLoading.value) return // 防止重复请求

    optionsLoading.value = true
    try {
      const response = await getCompanyOptionsApi()
      if (response?.data) {
        // 使用结构化赋值替代 Object.assign
        options.workCityOptions = response.data.workCityOptions || []
        options.companyTypeOptions = response.data.companyTypeOptions || []
        options.companyScaleOptions = response.data.companyScaleOptions || []
      }
    } catch (error) {
      handleApiError(error, "获取选项数据失败")
    } finally {
      optionsLoading.value = false
    }
  }

  // 获取公司详情（用于查看）
  const fetchCompanyDetail = async (companyId: number): Promise<CompanyDetail | null> => {
    // 参数验证
    if (!companyId || Number.isNaN(Number(companyId)) || Number(companyId) <= 0) {
      console.warn("无效的公司ID:", companyId)
      return null
    }

    if (detailLoading.value) return currentDetail.value // 防止重复请求

    detailLoading.value = true
    try {
      const response = await getCompanyDetailApi({ companyId })

      if (response?.data) {
        currentDetail.value = response.data
        return response.data
      }
      return null
    } catch (error) {
      handleApiError(error, "获取公司详情失败")
      return null
    } finally {
      detailLoading.value = false
    }
  }

  // 获取公司信息用于更新
  const fetchCompanyForUpdate = async (companyId: number): Promise<CreateOrUpdateCompanyRequest | null> => {
    // 参数验证
    if (!companyId || Number.isNaN(Number(companyId)) || Number(companyId) <= 0) {
      console.warn("无效的公司ID:", companyId)
      return null
    }

    if (detailLoading.value) return null // 防止重复请求

    detailLoading.value = true
    try {
      const response = await getCompanyForUpdateApi(companyId)

      if (response?.data) {
        return response.data
      }
      return null
    } catch (error) {
      handleApiError(error, "获取公司更新数据失败")
      return null
    } finally {
      detailLoading.value = false
    }
  }

  const findCompanyById = (id: number): CompanyItem | undefined => {
    if (!id || Number.isNaN(Number(id)) || Number(id) <= 0) {
      return undefined
    }
    return companyList.value.find(item => item.companyId === id)
  }

  // 创建公司
  const createCompany = async (data: CreateOrUpdateCompanyRequest): Promise<boolean> => {
    if (submitLoading.value) return false

    submitLoading.value = true
    const userStore = useUserStore()
    const requestData = {
      ...data,
      publishUserId: userStore.userInfo?.userId || 0
    }

    const response = await createCompanyApi(requestData)

    if (response?.code === 200) {
      ElMessage.success("公司创建成功")
      submitLoading.value = false
      // 移除内部fetchCompanyList调用，由父组件handleEditSuccess统一处理
      return true
    }
    submitLoading.value = false
    return false
  }

  // 更新公司
  const updateCompany = async (data: CreateOrUpdateCompanyRequest): Promise<boolean> => {
    if (submitLoading.value || !data.companyId) return false

    submitLoading.value = true
    const userStore = useUserStore()
    const requestData = {
      ...data,
      publishUserId: userStore.userInfo?.userId || 0
    }
    const response = await updateCompanyApi(requestData)

    if (response?.code === 200) {
      ElMessage.success("公司更新成功")
      // 先设置 submitLoading 为 false
      submitLoading.value = false

      // 保留详情更新逻辑，但移除列表刷新调用
      if (currentDetail.value && currentDetail.value.companyId === data.companyId) {
        fetchCompanyDetail(data.companyId)
      }
      // 移除内部fetchCompanyList调用，由父组件handleEditSuccess统一处理
      return true
    } else {
      ElMessage.error(response?.message || "公司更新失败")
      submitLoading.value = false
      return false
    }
  }

  // 删除公司
  const deleteCompany = async (companyId: number): Promise<boolean> => {
    if (submitLoading.value || !companyId) return false

    submitLoading.value = true
    try {
      const response = await deleteCompanyApi(companyId)

      if (response?.code === 200 && response?.data?.success) {
        ElMessage.success("公司删除成功")
        // 删除成功后刷新列表
        await fetchCompanyList(true)
        // 如果删除的是当前查看的详情，清除详情
        if (currentDetail.value && currentDetail.value.companyId === companyId) {
          clearCurrentDetail()
        }
        return true
      } else {
        ElMessage.error(response?.message || "公司删除失败")
        return false
      }
    } catch (error) {
      handleApiError(error, "公司删除失败")
      return false
    } finally {
      submitLoading.value = false
    }
  }

  // 重置查询参数
  const resetQueryParams = (): void => {
    Object.assign(queryParams, DEFAULT_QUERY_PARAMS)
  }

  // 更新查询参数
  const updateQueryParams = (params: Partial<CompanyListQuery>): void => {
    Object.assign(queryParams, params)
  }

  // 清除当前详情
  const clearCurrentDetail = (): void => {
    currentDetail.value = null
  }

  // 上传营业执照
  const uploadLicense = async (file: File, businessId: number = 0): Promise<any> => {
    try {
      const response = await uploadLicenseApi(file, businessId)
      console.log("上传营业执照响应:", response)

      if (response?.code === 200) {
        return { success: true, data: { url: response.data } }
      }
      return { success: false, message: response?.message || "上传失败" }
    } catch (error) {
      handleApiError(error, "上传营业执照失败")
      return { success: false }
    }
  }

  return {
    // 状态
    companyList,
    total,
    loading,
    detailLoading,
    optionsLoading,
    submitLoading,
    options,
    currentDetail,
    queryParams,
    // 方法
    fetchCompanyList,
    fetchOptions,
    fetchCompanyDetail,
    fetchCompanyForUpdate,
    findCompanyById,
    resetQueryParams,
    updateQueryParams,
    clearCurrentDetail,
    createCompany,
    updateCompany,
    deleteCompany,
    uploadLicense
  }
})

export function useCompanyStoreOutside() {
  return useCompanyStore(pinia)
}
